package com.gable.exhibition.controller;

import com.gable.common.util.*;
import com.gable.exhibition.service.EventService;
import com.gable.exhibition.util.ExceptionUtil;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.EventView;
import com.gable.exhibition.view.FileView;
import com.gable.exhibition.view.UserView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by mj on 2018/2/26.
 */
@Controller
@RequestMapping(value = "/event")
public class EventController {

    @Autowired
    EventService eventService;
    /**
     * 添加事件
     * @param request
     * @return
     */
    @RequestMapping(value = "/addEvent",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil addEvent(HttpServletRequest request, EventView eventView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.FAILED);
        try {
            Long keyType = eventView.getKeyType();                  //来源类型
            Long keyId = eventView.getKeyId();                      //来源ID
            String eventDateTime = eventView.getEventDateTime();    //事件时间
            String eventContent = eventView.getEventContent();      //事件类容
            String eventTitle = eventView.getEventTitle();          //事件标题
            Long userId = eventView.getUserId();                    //用户id
            if(keyType == null)
                return new ReturnResultUtil(500,MessageUtil.EVENTKEYTYPE);
            if(keyId == null)
                return new ReturnResultUtil(500,MessageUtil.EVENTKEYID);
            if(StringUtil.isEmpty(eventDateTime))
                return new ReturnResultUtil(500,MessageUtil.EVENTDATETIME);
            if(StringUtil.isEmpty(eventContent))
                return new ReturnResultUtil(500,MessageUtil.EVENTCONTENT);
            if(StringUtil.isEmpty(eventTitle))
                return new ReturnResultUtil(500,MessageUtil.EVENTTITLE);
            eventView.setCreatePerson(userId);
            eventView.setEventId(UUIDGenerator.getUniqueLong());

            //包含文件，上传文件
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            if (files != null && files.size() > 0) {
                String rootPath = request.getSession().getServletContext().getRealPath(java.io.File.separator);
                String fileType = null;
                if(!StringUtil.isEmpty(multipartRequest.getParameter("fileType"))){
                    fileType = multipartRequest.getParameter("fileType");
                }
                String fileDateStart =  multipartRequest.getParameter("fileDateStart");
                String fileDateEnd = multipartRequest.getParameter("fileDateEnd");
                String remark = multipartRequest.getParameter("remark");
                String type = multipartRequest.getParameter("type");
                List<FileView> fileList = new ArrayList<FileView>();
                Long ym = new Date().getTime();
                String filePath = "upload/" + ym;

                for (MultipartFile m : files) {
                    if(m.getBytes().length == 0){
                        return new ReturnResultUtil(500,MessageUtil.PLEASEUPLOADFILES);
                    }

                    String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".")+1);
                    String key = type+"/" + new Date().getTime()+"."+suffix;
                    boolean bl = FileUploadUtil.fileUpload(m.getBytes(), key);
                    if (!bl) {
                        return new ReturnResultUtil(500,MessageUtil.PLEASEUPLOADFILES);
                    }

                    key = FileUploadUtil.REALMNAME+"/"+key;

                    FileView file = new FileView();
                    file.setIsDel(0);
                    file.setCreatePerson(userId);
                    file.setEndDate(fileDateEnd);
                    file.setStartDate(fileDateStart);
                    file.setFileName(m.getOriginalFilename());
                    file.setFileId(UUIDGenerator.getUniqueLong());
                    file.setFileSize(m.getSize());
                    file.setFileSuffix(suffix);
                    file.setFileType(fileType);
                    file.setKeyId(eventView.getEventId());
                    file.setKeyType(1405L);
                    file.setFileUrl(key);
                    fileList.add(file);
                }
                eventView.setFileList(fileList);
            }
            resultUtil = eventService.addEvent(eventView);

        } catch (ExceptionUtil eu){
            return new ReturnResultUtil(eu.getRet(),eu.getMsg(),eu.getData());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    /**
     * 事件列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/eventList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil eventList(HttpServletRequest request, EventView eventView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
        try {
            Long userId = eventView.getUserId();
            Long keyId = eventView.getKeyId();
            Long keyType = eventView.getKeyType();
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                sessionUser = CacheData.getSessionUser(null,2);
            if(sessionUser == null)
                return new ReturnResultUtil(500,MessageUtil.USERIDDOESTNOEXIST);
            eventView.setUserId(sessionUser.getUserId());
            if(keyType == null)
                return new ReturnResultUtil(500,MessageUtil.EVENTKEYTYPE);
            if(keyId == null)
                return new ReturnResultUtil(500,MessageUtil.EVENTKEYID);
            resultUtil = eventService.eventList(eventView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    /**
     * 小程序添加事件
     * @param request
     * @return
     */
    @RequestMapping(value = "/addEventForWeChat",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil addEventForWeChat(HttpServletRequest request, EventView eventView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.FAILED);
        try {
            Long keyType = eventView.getKeyType();                  //来源类型
            Long keyId = eventView.getKeyId();                      //来源ID
            String eventDateTime = eventView.getEventDateTime();    //事件时间
            String eventContent = eventView.getEventContent();      //事件类容
            String eventTitle = eventView.getEventTitle();          //事件标题
            Long userId = eventView.getUserId();                    //用户id
            if(userId == null) {
                UserView sessionUser = CacheData.getSessionUser(null, 1);
                if(sessionUser != null)
                    userId = sessionUser.getUserId();
            }
            if(keyType == null)
                return new ReturnResultUtil(500,MessageUtil.EVENTKEYTYPE);
            if(keyId == null)
                return new ReturnResultUtil(500,MessageUtil.EVENTKEYID);
            if(StringUtil.isEmpty(eventDateTime))
                return new ReturnResultUtil(500,MessageUtil.EVENTDATETIME);
            if(StringUtil.isEmpty(eventContent))
                return new ReturnResultUtil(500,MessageUtil.EVENTCONTENT);
            if(StringUtil.isEmpty(eventTitle))
                return new ReturnResultUtil(500,MessageUtil.EVENTTITLE);
            eventView.setCreatePerson(userId);
            eventView.setEventId(UUIDGenerator.getUniqueLong());

            resultUtil = eventService.addEventForWeChat(eventView);

        } catch (ExceptionUtil eu){
            return new ReturnResultUtil(eu.getRet(),eu.getMsg(),eu.getData());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    /**
     * 删除事件
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteEvent",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil deleteEvent(HttpServletRequest request, EventView eventView){
        ReturnResultUtil resultUtil = null;
        try {
            resultUtil = new ReturnResultUtil(500, MessageUtil.FAILED);
            Long eventId = eventView.getEventId();
            if(eventId == null)
                return new ReturnResultUtil(500,MessageUtil.EVENTISNULL);
            resultUtil = eventService.deleteEvent(eventView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }
}
